package com.everflourish.yeah100.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.markingsystem.FragmentTopicSetting;
import com.everflourish.yeah100.entity.marking.Topic;
import com.everflourish.yeah100.entity.marking.TopicModel;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.TopicUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/6/15.
 * 时间：2016/6/15
 */
public class TopicSettingAdapter extends RecyclerView.Adapter<TopicSettingAdapter.TopicViewholder> {

    public static final String TOPIC = "topic";

    private LayoutInflater mInflater;
    private List<TopicModel> mList;
    private Context mContext;
    private FragmentTopicSetting mFragment;
    private ListPopupWindow mSubjectPopupWindow;

    public TopicSettingAdapter(Context context, List<TopicModel> list, FragmentTopicSetting fragment) {
        mInflater = LayoutInflater.from(context);
        mList = list;
        mContext = context;
        this.mFragment = fragment;
    }

    enum EditTextFlag {
        none, startNo, endNo, score, lackScore, topicType
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public TopicViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.item_topic_setting, parent, false);
        TopicViewholder viewHolder = new TopicViewholder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(TopicViewholder holder, int position) {
        TopicModel topicModel = mList.get(position);
        Topic topic = topicModel.getTopic();
        holder.mTopicNameTv.setText(topic.getTopicName());
        holder.mTopicNumberTv.setText(topic.getTopicBegin() + "-" + topic.getTopicEnd());
        holder.mTopicScoreTv.setText(topic.getTopicPoint() + "");
        holder.mTopicTypeTv.setText(topic.getTopicTypeText());
        holder.mTopicScoreLackTv.setText(topic.getTopicPartPoint() + "");

        setVisibility(holder, true, false);
        if (topicModel.isAdd() || topicModel.isEdit()) {
            setLastData(holder, topicModel);
            setVisibility(holder, false, true);
        }
        if (holder.mTopicTypeEt.getText().toString().equals("多选题")) {
            holder.mTopicScoreLackTil.setVisibility(View.VISIBLE);
        } else {
            holder.mTopicScoreLackTil.setVisibility(View.GONE);
        }
        if (topic.getTopicTypeText() != null && topic.getTopicTypeText().equals("多选题")) {
            holder.mTopicScoreLackLl.setVisibility(View.VISIBLE);
            holder.mTopicScoreLackEt.setText(topic.getTopicPartPoint() + "");
        } else {
            holder.mTopicScoreLackLl.setVisibility(View.GONE);
        }
        if (holder.mTopicTypeTv.getText().toString().equals("主观题") || topic.getTopicType() == 3) {
            holder.mTopicScoreTitleTv.setText("总分值");
            holder.mTopicScoreTil.setHint("总分值");
        } else {
            holder.mTopicScoreTitleTv.setText("每题分值");
            holder.mTopicScoreTil.setHint("每题分值");
        }
        holder.mTopicNormalLl.setOnClickListener(new MyOnclickListener(holder, position, topicModel));
        holder.mTopicCompleteBt.setOnClickListener(new MyOnclickListener(holder, position, topicModel));
        holder.mTopicCancleteBt.setOnClickListener(new MyOnclickListener(holder, position, topicModel));
        holder.mTopicTypeEt.setOnClickListener(new MyOnclickListener(holder, position, topicModel));
        holder.mTopicNumberEt.setOnClickListener(new MyOnclickListener(holder, position, topicModel));
        holder.mTopicDeleteLl.setOnClickListener(new MyOnclickListener(holder, position, topicModel));
//        holder.mTopicDeleteIv.setOnClickListener(new MyOnclickListener(holder, position, topicModel));
//        showDialogItems(holder);
    }

    /**
     * 设置编辑的数据
     *
     * @param viewholder
     * @param topicModel
     */
    private void setLastData(TopicViewholder viewholder, TopicModel topicModel) {
        Topic topic = topicModel.getTopic();
        viewholder.mTopicNameEt.setText(topic.getTopicName());
        viewholder.mTopicNumberEt.setText(topic.getTopicBegin() + "-" + topic.getTopicEnd());
        viewholder.mTopicTypeEt.setText(topic.getTopicTypeText());
        viewholder.mTopicScoreEt.setText(topic.getTopicPoint() + "");
    }

    /**
     * 选择科目lsit弹出框
     */
    private void showDialogItems(final TopicViewholder viewholder) {
        String[] type = {"单选题", "多选题", "主观题"};
        final List<String> items = new ArrayList<String>();
        for (String s : type) {
            items.add(s);
        }
        mSubjectPopupWindow = new ListPopupWindow(mFragment.mMarkingMenuActivity);
        mSubjectPopupWindow.setAdapter(new ArrayAdapter<String>(mFragment.mMarkingMenuActivity, R.layout.item_subject_popup, items));
        mSubjectPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSubjectPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSubjectPopupWindow.setAnchorView(viewholder.mTopicTypeEt);//设置ListPopupWindow的锚点，即关联PopupWindow的显示位置和这个锚点
        mSubjectPopupWindow.setModal(true);// 设置是否是模式
        mSubjectPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 1) {  //  多选题
                    viewholder.mTopicScoreLackTil.setVisibility(View.VISIBLE);
                } else {
                    viewholder.mTopicScoreLackTil.setVisibility(View.GONE);
                }
                if (position == 2) {  // 主观题
//                    viewholder.mTopicScoreEt.setHint("总分值");
                    viewholder.mTopicScoreTil.setHint("总分值");
                } else {
//                    viewholder.mTopicScoreEt.setHint("每题分值");
                    viewholder.mTopicScoreTil.setHint("每题分值");
                }
                viewholder.mTopicTypeEt.setText(items.get(position));
                mSubjectPopupWindow.dismiss();
            }
        });
        mSubjectPopupWindow.show();
    }

    /**
     * 设置显示，隐藏
     *
     * @param viewholder
     * @param isNormalVisible
     * @param isAddVisible
     */
    private void setVisibility(TopicViewholder viewholder, boolean isNormalVisible, boolean isAddVisible) {
        if (isNormalVisible) {
            viewholder.mTopicNormalLl.setVisibility(View.VISIBLE);
        } else {
            viewholder.mTopicNormalLl.setVisibility(View.GONE);
        }
        if (isAddVisible) {
            viewholder.mTopicAddLl.setVisibility(View.VISIBLE);
        } else {
            viewholder.mTopicAddLl.setVisibility(View.GONE);
        }
    }

    public class TopicViewholder extends RecyclerView.ViewHolder {

        // 正常部分
        public TextView mTopicNameTv;
        public TextView mTopicNumberTv;
        public TextView mTopicTypeTv;
        public TextView mTopicScoreTv;
        public TextView mTopicScoreLackTv;
        public TextView mTopicScoreTitleTv;
        public LinearLayout mTopicScoreLackLl;
        public LinearLayout mTopicNormalLl;
        public LinearLayout mTopicAddLl;
        public Button mTopicCompleteBt;
        public Button mTopicCancleteBt;
        public ImageView mTopicDeleteIv;
        public LinearLayout mTopicDeleteLl;

        //  编辑部分
        public EditText mTopicNameEt;
        public EditText mTopicNumberEt;
        public EditText mTopicScoreEt;
        public EditText mTopicTypeEt;
        public EditText mTopicScoreLackEt;
        public TextInputLayout mTopicNameTil;
        public TextInputLayout mTopicNumberTil;
        public TextInputLayout mTopicScoreTil;
        public TextInputLayout mTopicTypeTil;
        public TextInputLayout mTopicScoreLackTil;

        public TopicViewholder(View itemView) {
            super(itemView);
            //  正常部分
            mTopicNameTv = (TextView) itemView.findViewById(R.id.topic_name_tv);
            mTopicNumberTv = (TextView) itemView.findViewById(R.id.topic_number_tv);
            mTopicScoreTv = (TextView) itemView.findViewById(R.id.topic_score_tv);
            mTopicTypeTv = (TextView) itemView.findViewById(R.id.topic_type_tv);
            mTopicScoreLackTv = (TextView) itemView.findViewById(R.id.topic_lack_score_tv);
            mTopicScoreTitleTv = (TextView) itemView.findViewById(R.id.topic_score_title);
            mTopicScoreLackLl = (LinearLayout) itemView.findViewById(R.id.topic_lack_score_ll);
            mTopicAddLl = (LinearLayout) itemView.findViewById(R.id.fragment_topic_edit);
            mTopicNormalLl = (LinearLayout) itemView.findViewById(R.id.fragment_topic_normal);
            mTopicDeleteIv = (ImageView) itemView.findViewById(R.id.topic_delete_bt);
            mTopicDeleteLl = (LinearLayout) itemView.findViewById(R.id.topic_delete_ll);

            //  添加部分
            mTopicNameEt = (EditText) itemView.findViewById(R.id.topic_name_et);
            mTopicNumberEt = (EditText) itemView.findViewById(R.id.topic_number_et);
            mTopicScoreEt = (EditText) itemView.findViewById(R.id.topic_score_et);
            mTopicTypeEt = (EditText) itemView.findViewById(R.id.topic_type_et);
            mTopicScoreLackEt = (EditText) itemView.findViewById(R.id.topic_lack_score_et);
            mTopicCompleteBt = (Button) itemView.findViewById(R.id.topic_complete_bt);
            mTopicCancleteBt = (Button) itemView.findViewById(R.id.topic_cancel_bt);

            mTopicNameTil = (TextInputLayout) itemView.findViewById(R.id.topic_name_til);
            mTopicNumberTil = (TextInputLayout) itemView.findViewById(R.id.topic_number_til);
            mTopicScoreTil = (TextInputLayout) itemView.findViewById(R.id.topic_score_til);
            mTopicTypeTil = (TextInputLayout) itemView.findViewById(R.id.topic_type_til);
            mTopicScoreLackTil = (TextInputLayout) itemView.findViewById(R.id.topic_lack_score_til);
        }
    }

    class MyOnclickListener implements View.OnClickListener {

        private TopicViewholder viewHolder;
        private int position;
        private TopicModel topicModel;

        public MyOnclickListener(TopicViewholder viewHolder, int position, TopicModel topicModel) {
            this.viewHolder = viewHolder;
            this.position = position;
            this.topicModel = topicModel;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.fragment_topic_normal:
                    for (TopicModel topic : mList) {
                        topic.setIsEdit(false);
                    }
                    topicModel.setIsEdit(true);
                    notifyDataSetChanged();
                    mFragment.mTopicRecyclerView.smoothScrollToPosition(position);
                    break;
                case R.id.topic_complete_bt:
                    String topicName = viewHolder.mTopicNameEt.getText().toString();
                    String topicNumber = viewHolder.mTopicNumberEt.getText().toString().trim();
                    String topicScore = viewHolder.mTopicScoreEt.getText().toString().trim();
                    String topicType = viewHolder.mTopicTypeEt.getText().toString().trim();
                    String topicScoreLack = viewHolder.mTopicScoreLackEt.getText().toString().trim();
                    if (TextUtils.isEmpty(topicName)) {
                        viewHolder.mTopicNameTil.setError("请输入题目名称");
                        return;
                    }
                    if (TextUtils.isEmpty(topicNumber)) {
                        viewHolder.mTopicNumberTil.setError("请选择起止题号");
                        return;
                    }
                    String[] topicNumberStr = topicNumber.split("-");
                    int beginNum = Integer.valueOf(topicNumberStr[0]);
                    int endNum = Integer.valueOf(topicNumberStr[1]);
                    if (beginNum > endNum) {
                        viewHolder.mTopicNumberTil.setError("开始题号需小于等于终止题号");
                        return;
                    } else {
                        viewHolder.mTopicNumberTil.setErrorEnabled(false);
                        viewHolder.mTopicNumberTil.setError(null);
                    }
                    if (!TopicUtil.judgeIsAvailableTopic(beginNum, endNum, position, mFragment.mTopics)) {
                        viewHolder.mTopicNumberTil.setError("起始题号和终止题号范围不能包含已设题号结束题号");
                        return;
                    } else {
                        viewHolder.mTopicNumberTil.setErrorEnabled(false);
                        viewHolder.mTopicNumberTil.setError(null);
                    }
                    if (TextUtils.isEmpty(topicType)) {
                        viewHolder.mTopicTypeTil.setError("请选择题目类型");
                        return;
                    } else {
                        viewHolder.mTopicTypeTil.setErrorEnabled(false);
                        viewHolder.mTopicTypeTil.setError(null);
                    }
                    if (TextUtils.isEmpty(topicScore)) {
                        viewHolder.mTopicScoreTil.setError("请输入每题分值");
                        return;
                    } else {
                        viewHolder.mTopicScoreTil.setErrorEnabled(false);
                        viewHolder.mTopicScoreTil.setError(null);
                    }
                    if (TextUtils.isEmpty(topicScoreLack)) {
                        viewHolder.mTopicScoreLackTil.setError("请输入缺选分值");
                        return;
                    } else {
                        viewHolder.mTopicScoreLackTil.setErrorEnabled(false);
                        viewHolder.mTopicScoreLackTil.setError(null);
                    }
                    float topicScoreInt = StringUtil.parseFloat(topicScore, -1.0f);
                    float topicScoreLackInt = StringUtil.parseFloat(topicScoreLack, -1.0f);
                    if (topicScoreLackInt >= topicScoreInt) {
                        viewHolder.mTopicScoreLackTil.setError("缺选分值不能大于或等于每题分值");
                        return;
                    } else {
                        viewHolder.mTopicScoreLackTil.setErrorEnabled(false);
                        viewHolder.mTopicScoreLackTil.setError(null);
                    }
                    Topic topic = topicModel.getTopic();
                    topic.setTopicName(topicName);
                    topic.setTopicType(topic.getTopicType(topicType));
                    topic.setTopicBegin(beginNum);
                    topic.setTopicEnd(endNum);
                    topic.setTopicPoint(StringUtil.parseFloat(topicScore, -1f));
                    topic.setTopicPartPoint(StringUtil.parseFloat(topicScoreLack, -1f));
                    mFragment.uploadTopicsRequest(topicModel);
                    break;
                case R.id.topic_type_et:
                    showDialogItems(viewHolder);
                    break;
                case R.id.topic_cancel_bt:
                    if (topicModel.isEdit()) {
                        topicModel.setIsEdit(false);
                    } else if (topicModel.isAdd()) {
                        mList.remove(topicModel);
                    }
                    notifyDataSetChanged();
                    break;
                case R.id.topic_delete_ll:
                    mFragment.deleteTopicsRequest(topicModel);
                    break;
                case R.id.topic_number_et:
                    String topicNumbers = viewHolder.mTopicNumberEt.getText().toString();
                    String[] topicArray = topicNumbers.split("-");
                    onTileWidthHeightClicked(viewHolder, StringUtil.parseInt(topicArray[0], -1),
                            StringUtil.parseInt(topicArray[1], -1));
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 题号选择对话框
     */
    private void onTileWidthHeightClicked(final TopicViewholder holder, int currentMinNo, int currentMaxNo) {
        final LinearLayout layout = new LinearLayout(mContext);
        layout.setOrientation(LinearLayout.HORIZONTAL);
        final NumberPicker pickerWidth = new NumberPicker(mContext);
        pickerWidth.setMinValue(1);
        pickerWidth.setMaxValue(200);
        pickerWidth.setWrapSelectorWheel(false);
        pickerWidth.setValue(currentMinNo);
        final NumberPicker pickerHeight = new NumberPicker(mContext);
        pickerHeight.setMinValue(1);
        pickerHeight.setMaxValue(200);
        pickerHeight.setWrapSelectorWheel(false);
        pickerHeight.setValue(currentMaxNo);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1);
        layout.addView(pickerWidth, params);
        layout.addView(pickerHeight, params);
        new AlertDialog.Builder(mContext)
                .setView(layout)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        holder.mTopicNumberEt.setText(pickerWidth.getValue() + "-" + pickerHeight.getValue());
                    }
                })
                .show();
    }
}